package com.seio.edc.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.nova.edc.model.system.Description;
import com.nova.edc.model.system.ModelConstant;
import com.nova.edc.service.energy.GatherSummaryService;
import com.nova.edc.service.energy.OverallStatisticsService;
import com.nova.edc.service.system.DescriptionService;
import com.nova.edc.service.system.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.nova.edc.model.system.CustomerInfo;
import com.nova.edc.model.system.Login;
import com.nova.edc.service.energy.BillStatisticsService;
import com.nova.edc.service.system.CustomerInfoService;
import com.nova.edc.service.system.RoleMenuService;
import com.seio.edc.common.MD5;
import com.seio.edc.util.DateTimeUtil;

/**
 * <p/>
 * Project Name: EMS智能节能监测平台 <br>
 * Description: 登录成功后的主页面
 */
@Controller
public class HomeController {

    @Autowired
    private RoleMenuService novaRoleMenuService;

    @Autowired
    private com.nova.edc.service.system.LoginService novaLoginService;

    @Autowired
    private CustomerInfoService novaCustomerInfoService;

    @Autowired
    private BillStatisticsService novaBillStatisticsService;

    @Autowired
    private OverallStatisticsService novaOverallStatisticsService;

    @Autowired
    private GatherSummaryService novaGatherSummaryService;

    @Autowired
    private DescriptionService novaDescriptionService;

    @Autowired
    private RoleService novaRoleService;

    /**
     * 显示登录画面
     */
    @RequestMapping(value = "/index")
    public ModelAndView index(HttpServletRequest request, HttpSession session,
                              ModelMap modelMap) {
        // 清除session
        Enumeration<String> em = request.getSession().getAttributeNames();
        while (em.hasMoreElements()) {
            request.getSession().removeAttribute(em.nextElement().toString());
        }

        request.getSession().invalidate();
        return new ModelAndView("index", modelMap);
    }

    /**
     * 根据 url 显示登录画面
     */
    @RequestMapping(value = "/toEvery")
    public ModelAndView toEvery(HttpServletRequest request,
                                HttpSession session, ModelMap modelMap) {

        String name = request.getParameter("name");
        String password = MD5.Md5(request.getParameter("password")); // 加密完的进行匹配
        // 用户是否存在判断
        Login login = new Login();
        login.setUsername(name);
        login.setPassword(password);
        login.setScrapped(0);
        login = novaLoginService.getLogin(login);
        if (login != null) {
            // 登录用户所属公司code设定到session中
            if (login.getCustomerinfoid() != null && login.getCustomerinfoid() != 0) {
                CustomerInfo customerInfo = novaCustomerInfoService.getById(login
                        .getCustomerinfoid());
                if (customerInfo != null) {
                    session.setAttribute("companycode",
                            customerInfo.getCompanycode());
                    session.setAttribute("customername",
                            customerInfo.getCustomername());
                    session.setAttribute("customerinfoid",
                            login.getCustomerinfoid());
                }
                session.setAttribute(
                        "leftmenus",
                        novaRoleMenuService.findMenuByRole(login.getRoleid(), customerInfo.getCustomerinfotype(), customerInfo.getArchitecturetype()));
            } else {
                session.setAttribute(
                        "leftmenus",
                        novaRoleMenuService.findMenuByRole(login.getRoleid(), null, null));
            }
            session.setAttribute("roleid", login.getRoleid());
            // 登录信息存在session中
            session.setAttribute("loginname", name);
            session.setAttribute("sessionLogin", login);
            // 获取登录用户相应的节省的电费和价格
            List<CustomerInfo> customerInfos = null;
            if (login.getRoletype() == ModelConstant.ROLE_GROUP) {
                customerInfos = novaCustomerInfoService.findByGroupcode(login.getGroupcode());
            } else {
                customerInfos = novaCustomerInfoService
                        .findCustomerInfoListByRole(name, null, "", "");
            }

            List<Integer> customerInfoIds = new ArrayList<Integer>();
            for (CustomerInfo info : customerInfos) {
                customerInfoIds.add(info.getId());
            }
//            Map<String, BigDecimal> statistics = novaGatherSummaryService
//                    .getAllStatistics(customerInfoIds, ModelConstant.MIN_DATE, ModelConstant.MAX_DATE);
//            modelMap.put("statistics", statistics);
//            Map<String, BigDecimal> unitStatistics = novaGatherSummaryService
//                    .getUnitStatistics(
//                            DateTimeUtil.getNowTime(DateTimeUtil.YYYY_MM_DD),
//                            DateTimeUtil.addDays(-7, DateTimeUtil.YYYY_MM_DD));
//
//            modelMap.put("unitStatistics", unitStatistics);
            request.getSession().setAttribute("menuid", 0);
            Integer systemId = novaRoleService.findByType(ModelConstant.ROLE_SYSTEM).get(0).getId();
            Integer customerinfoid = novaLoginService.findByRoleId(systemId).get(0).getCustomerinfoid();
            Description description = novaDescriptionService.getByLogin(login, customerinfoid);
            modelMap.put("description", description);
            return new ModelAndView("description/companyDescription");
        } else {
            modelMap.put("errormsg", "用户名或者密码不正确");
            return new ModelAndView("index", modelMap);
        }
    }

    @RequestMapping(value = "getTotleData.shtml")
    @ResponseBody
    public Map<String, BigDecimal> userNameVali(HttpServletRequest request,
                                                HttpSession session) {
        // 获取登录用户相应的节省的电费和价格
        String loginname = (String) session.getAttribute("loginname");
        List<CustomerInfo> customerInfos = novaCustomerInfoService
                .findCustomerInfoListByRole(loginname, null, "", "");
        List<Integer> customerInfoIds = new ArrayList<Integer>();
        for (CustomerInfo info : customerInfos) {
            customerInfoIds.add(info.getId());
        }
        Map<String, BigDecimal> statistics = novaGatherSummaryService
                .getAllStatistics(customerInfoIds, ModelConstant.MIN_DATE, ModelConstant.MAX_DATE);
        return statistics;
    }

    @RequestMapping(value = "getEnergy.shtml")
    @ResponseBody
    public Map<String, BigDecimal> getEnergy(HttpServletRequest request,
                                             HttpSession session) {
        Login login = (Login) session.getAttribute("sessionLogin");
        List<CustomerInfo> customerInfos = null;
        if (login.getRoletype() == ModelConstant.ROLE_GROUP) {
            customerInfos = novaCustomerInfoService.findByGroupcode(login.getGroupcode());
        } else {
            customerInfos = novaCustomerInfoService
                    .findCustomerInfoListByRole(login.getUsername(), null, "", "");
        }

        List<Integer> customerInfoIds = new ArrayList<Integer>();
        for (CustomerInfo info : customerInfos) {
            customerInfoIds.add(info.getId());
        }
        Map<String, BigDecimal> statistics = novaGatherSummaryService
                .getAllStatistics(customerInfoIds, ModelConstant.MIN_DATE, ModelConstant.MAX_DATE);
        return statistics;
    }

    @RequestMapping(value = "getUtilStatic.shtml")
    @ResponseBody
    public Map<String, BigDecimal> getUtilStatic(HttpServletRequest request,
                                             HttpSession session) {
        Login login = (Login) session.getAttribute("sessionLogin");
        List<CustomerInfo> customerInfos = null;
        if (login.getRoletype() == ModelConstant.ROLE_GROUP) {
            customerInfos = novaCustomerInfoService.findByGroupcode(login.getGroupcode());
        } else {
            customerInfos = novaCustomerInfoService
                    .findCustomerInfoListByRole(login.getUsername(), null, "", "");
        }

        List<Integer> customerInfoIds = new ArrayList<Integer>();
        for (CustomerInfo info : customerInfos) {
            customerInfoIds.add(info.getId());
        }
            Map<String, BigDecimal> unitStatistics = novaGatherSummaryService
                    .getUnitStatistics(
                            customerInfoIds,
                            DateTimeUtil.getNowTime(DateTimeUtil.YYYY_MM_DD),
                            DateTimeUtil.addDays(-7, DateTimeUtil.YYYY_MM_DD));
        return unitStatistics;
    }
}
